<template>
  <div class="recording-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>录像管理</span>
          <div class="header-controls">
            <el-select v-model="selectedDevice" placeholder="选择设备" @change="onDeviceChange">
              <el-option
                v-for="device in devices"
                :key="device.id"
                :label="device.name"
                :value="device.id"
              />
            </el-select>
            <el-select v-model="selectedChannel" placeholder="选择通道" @change="onChannelChange">
              <el-option
                v-for="channel in channels"
                :key="channel.id"
                :label="channel.name"
                :value="channel.id"
              />
            </el-select>
            <el-button type="primary" @click="refreshRecordings">
              刷新录像
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 录像控制 -->
      <div class="recording-controls">
        <el-card class="control-card">
          <template #header>
            <span>录像控制</span>
          </template>
          <div class="control-buttons">
            <el-button 
              type="success" 
              :disabled="!selectedChannel || isRecording"
              @click="startRecording"
            >
              <el-icon><VideoPlay /></el-icon>
              开始录像
            </el-button>
            <el-button 
              type="danger" 
              :disabled="!selectedChannel || !isRecording"
              @click="stopRecording"
            >
              <el-icon><VideoPause /></el-icon>
              停止录像
            </el-button>
            <el-tag v-if="isRecording" type="success" effect="dark">
              <el-icon><VideoPlay /></el-icon>
              录像中...
            </el-tag>
          </div>
        </el-card>
      </div>
      
      <!-- 查询条件 -->
      <div class="search-filters">
        <el-form :model="searchForm" inline>
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="searchForm.startTime"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="searchForm.endTime"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="录像类型">
            <el-select v-model="searchForm.recordType" placeholder="选择录像类型">
              <el-option label="全部" value="" />
              <el-option label="手动录像" value="manual" />
              <el-option label="定时录像" value="schedule" />
              <el-option label="事件录像" value="event" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchRecordings">
              查询
            </el-button>
            <el-button @click="resetSearch">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 录像列表 -->
      <div class="recording-list">
        <el-table 
          :data="recordings" 
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="fileName" label="文件名" min-width="200" />
          <el-table-column prop="startTime" label="开始时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.startTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="duration" label="时长" width="100">
            <template #default="{ row }">
              {{ formatDuration(row.duration) }}
            </template>
          </el-table-column>
          <el-table-column prop="fileSize" label="文件大小" width="120">
            <template #default="{ row }">
              {{ formatFileSize(row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column prop="recordType" label="录像类型" width="100">
            <template #default="{ row }">
              <el-tag :type="getRecordTypeColor(row.recordType)">
                {{ getRecordTypeText(row.recordType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button size="small" @click="playRecording(row)">
                播放
              </el-button>
              <el-button size="small" type="primary" @click="downloadRecording(row)">
                下载
              </el-button>
              <el-button size="small" type="danger" @click="deleteRecording(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 批量操作 -->
        <div class="batch-operations" v-if="selectedRecordings.length > 0">
          <el-alert
            :title="`已选择 ${selectedRecordings.length} 个录像文件`"
            type="info"
            show-icon
            :closable="false"
          />
          <div class="batch-buttons">
            <el-button type="primary" @click="batchDownload">
              批量下载
            </el-button>
            <el-button type="danger" @click="batchDelete">
              批量删除
            </el-button>
          </div>
        </div>
        
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
    
    <!-- 播放对话框 -->
    <el-dialog 
      v-model="playDialogVisible" 
      title="录像播放" 
      width="80%"
      :before-close="closePlayDialog"
    >
      <div class="video-player-container">
        <video 
          ref="playVideoRef"
          controls 
          autoplay
          class="recording-player"
          :src="playUrl"
        >
          您的浏览器不支持视频播放
        </video>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { VideoPlay, VideoPause } from '@element-plus/icons-vue'
import { 
  getRecordings, 
  startRecording as apiStartRecording, 
  stopRecording as apiStopRecording,
  downloadRecording as apiDownloadRecording,
  deleteRecording as apiDeleteRecording
} from '@/api/recording'
import { getDevices } from '@/api/device'
import { getChannelsByDevice } from '@/api/channel'

const loading = ref(false)
const isRecording = ref(false)
const selectedDevice = ref('')
const selectedChannel = ref('')
const playDialogVisible = ref(false)
const playUrl = ref('')
const playVideoRef = ref(null)

const devices = ref([])
const channels = ref([])
const recordings = ref([])
const selectedRecordings = ref([])

const searchForm = reactive({
  startTime: '',
  endTime: '',
  recordType: ''
})

const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 加载设备列表
const loadDevices = async () => {
  try {
    const response = await getDevices()
    devices.value = response.data.content || []
  } catch (error) {
    ElMessage.error('加载设备列表失败')
  }
}

// 设备变化处理
const onDeviceChange = async () => {
  selectedChannel.value = ''
  channels.value = []
  recordings.value = []
  
  if (!selectedDevice.value) return
  
  try {
    const response = await getChannelsByDevice(selectedDevice.value)
    channels.value = response.data || []
  } catch (error) {
    ElMessage.error('加载通道列表失败')
  }
}

// 通道变化处理
const onChannelChange = () => {
  if (selectedChannel.value) {
    loadRecordings()
  }
}

// 加载录像列表
const loadRecordings = async () => {
  if (!selectedChannel.value) return
  
  loading.value = true
  try {
    const params = {
      channelId: selectedChannel.value,
      page: pagination.page - 1,
      size: pagination.size,
      ...searchForm
    }
    
    const response = await getRecordings(params)
    recordings.value = response.data.content || []
    pagination.total = response.data.totalElements || 0
  } catch (error) {
    ElMessage.error('加载录像列表失败')
  } finally {
    loading.value = false
  }
}

// 刷新录像
const refreshRecordings = () => {
  loadRecordings()
}

// 搜索录像
const searchRecordings = () => {
  pagination.page = 1
  loadRecordings()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    startTime: '',
    endTime: '',
    recordType: ''
  })
  searchRecordings()
}

// 开始录像
const startRecording = async () => {
  try {
    await apiStartRecording(selectedChannel.value)
    isRecording.value = true
    ElMessage.success('录像开始成功')
  } catch (error) {
    ElMessage.error('开始录像失败')
  }
}

// 停止录像
const stopRecording = async () => {
  try {
    await apiStopRecording(selectedChannel.value)
    isRecording.value = false
    ElMessage.success('录像停止成功')
    // 刷新录像列表
    setTimeout(() => {
      loadRecordings()
    }, 1000)
  } catch (error) {
    ElMessage.error('停止录像失败')
  }
}

// 播放录像
const playRecording = (recording) => {
  playUrl.value = recording.playUrl || ''
  playDialogVisible.value = true
}

// 关闭播放对话框
const closePlayDialog = () => {
  if (playVideoRef.value) {
    playVideoRef.value.pause()
  }
  playDialogVisible.value = false
  playUrl.value = ''
}

// 下载录像
const downloadRecording = async (recording) => {
  try {
    const response = await apiDownloadRecording(recording.id)
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.download = recording.fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('下载开始')
  } catch (error) {
    ElMessage.error('下载失败')
  }
}

// 删除录像
const deleteRecording = async (recording) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除录像文件 "${recording.fileName}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await apiDeleteRecording(recording.id)
    ElMessage.success('删除成功')
    loadRecordings()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 选择变化处理
const handleSelectionChange = (selection) => {
  selectedRecordings.value = selection
}

// 批量下载
const batchDownload = async () => {
  for (const recording of selectedRecordings.value) {
    await downloadRecording(recording)
    // 添加延迟避免并发过多
    await new Promise(resolve => setTimeout(resolve, 500))
  }
}

// 批量删除
const batchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRecordings.value.length} 个录像文件吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    for (const recording of selectedRecordings.value) {
      await apiDeleteRecording(recording.id)
    }
    
    ElMessage.success('批量删除成功')
    loadRecordings()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadRecordings()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadRecordings()
}

// 格式化函数
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString()
}

const formatDuration = (duration) => {
  if (!duration) return '-'
  const hours = Math.floor(duration / 3600)
  const minutes = Math.floor((duration % 3600) / 60)
  const seconds = duration % 60
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
}

const formatFileSize = (size) => {
  if (!size) return '-'
  const units = ['B', 'KB', 'MB', 'GB']
  let index = 0
  while (size >= 1024 && index < units.length - 1) {
    size /= 1024
    index++
  }
  return `${size.toFixed(2)} ${units[index]}`
}

const getRecordTypeColor = (type) => {
  const colors = {
    manual: 'primary',
    schedule: 'success',
    event: 'warning'
  }
  return colors[type] || 'info'
}

const getRecordTypeText = (type) => {
  const texts = {
    manual: '手动',
    schedule: '定时',
    event: '事件'
  }
  return texts[type] || '未知'
}

onMounted(() => {
  loadDevices()
})
</script>

<style scoped>
.recording-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-controls {
  display: flex;
  gap: 10px;
  align-items: center;
}

.recording-controls {
  margin-bottom: 20px;
}

.control-card {
  background: #f8f9fa;
}

.control-buttons {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-filters {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.recording-list {
  margin-top: 20px;
}

.batch-operations {
  margin: 20px 0;
  padding: 15px;
  background: #f0f9ff;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.batch-buttons {
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.video-player-container {
  display: flex;
  justify-content: center;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
}

.recording-player {
  width: 100%;
  max-height: 500px;
  object-fit: contain;
}
</style>